package com.shop.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.domain.Order;
import com.shop.domain.SeckillProduct;
import com.shop.feign.OrderFeign;
import com.shop.seckill.config.RabbitConfig;
import com.shop.seckill.service.SecKillOrderService;
import com.shop.seckill.utils.CustomMessageSender;
import com.shop.util.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SecKillOrderServiceImpl implements SecKillOrderService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CustomMessageSender customMessageSender;
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private TokenDecode tokenDecode;
    @Override
    public boolean add(Order order,String random) {
        String string = tokenDecode.getUserInfo().get("user_name");
        order.setBuyerName(string);
        //下单接口隐藏
        String string1 = redisTemplate.opsForValue().get("random_" + string).toString();
        if(string1==null || !string1.equals(random)){
            return false;
        }
        // 防止恶意刷单
        String key = "seckill_user_" + order.getBuyerName()+"_id_"+order.getProductId();
        Long increment = redisTemplate.opsForValue().increment(key, 1);
        if(increment != 1){
            return false;
        }
        // 有效期5分钟
        redisTemplate.expire(key,5, TimeUnit.MINUTES);

        //防止相同商品重复秒杀
        Order select = new Order();
        select.setBuyerName(order.getBuyerName());
        select.setProductId(order.getProductId());
        List<Order> data = orderFeign.selectList(select).getData();
        if(data!=null&&data.size()>0){
            return false;
        }

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH");
        String hour = sdf1.format(date);
        // 查询库存够不够
        Object o = redisTemplate.opsForValue().get("Inventory_"+order.getProductId());
        if(o == null || Integer.valueOf(o.toString())<order.getNum()){
            return false;
        }
        // 减秒杀商品的库存
        Long decrement = redisTemplate.opsForValue().decrement("Inventory_" + order.getProductId());
        if(decrement < 0){
            return false;
        }
        if(decrement == 0){
            // 卖完了 删除redis中对应的信息
            redisTemplate.delete("Inventory_" + order.getProductId());
        }
        Object o1 = redisTemplate.boundHashOps(format + hour + ":00").get(order.getProductId());
        SeckillProduct seckillProduct = JSONObject.parseObject(JSON.toJSONString(o1), SeckillProduct.class);
        order.setType(2); // 2表示订单类型是秒杀订单
        order.setMoney(BigDecimal.valueOf(seckillProduct.getSeckillMoney()*order.getNum()));
        order.setStatus(0); // 表示未付款

        customMessageSender.sendMessage(RabbitConfig.SECKILL_EXCHANGE,RabbitConfig.SECKILL_QUEUE,JSON.toJSONString(order));
        return true;
    }
}
